import { useEffect, useState } from 'react'
import { Table, Button, Space } from 'antd';

import Delete from "../../components/Delete"
import Edit from "../../components/Edit"

export interface IGood{ 
  key:string
  id: number
  inventory: number
  itemName: string
  type: string
}

function Storage(): JSX.Element {
  const [goodsList, setGoodsList] = useState<IGood[]>([]);
  const [isModalVisible, setIsModalVisible] = useState<boolean>(false);
  const [currentGood, setCurrentGood] = useState<IGood>();
  useEffect(()=>{
    for(let i = 0;i<20;i++){
      setGoodsList(prevGoodsList=>{
        return [{
          key: i+"goods",
          id: i,
          inventory: i,
          itemName: "name"+i,
          type: "type"+i
        },...prevGoodsList]
      })
    }
    
  },[])
  const deleteItem = (id:number) =>{
    setGoodsList(prevGoodsList => prevGoodsList.filter(good=>good.id !== id));
  }
  const setVisible = (visible:boolean, good?: IGood) => {
    setIsModalVisible(visible);
    setCurrentGood(good);
    //@ts-ignore
    setGoodsList(prevGoodsList => prevGoodsList.map((item:IGood)=> good.id === item.id ? good : item))
  }
  const columns = [
    {
      title: 'Id',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: 'Inventory',
      dataIndex: 'inventory',
      key: 'inventory',
    },
    {
      title: 'ItemName',
      dataIndex: 'itemName',
      key: 'itemName',
    },
    {
      title: 'Type',
      dataIndex: 'type',
      key: 'type',
    },
    {
      title: 'Action',
      key: 'action',
      render: (good:IGood) => (
        <Space size="middle">
          <Button type="primary" onClick={()=>setVisible(true, good)}>编辑</Button>
          <Delete id={good.id} callback={ deleteItem }></Delete>
        </Space>
      ),
    },
  ];
  
  return (
    <>
      <Edit isModalVisible={isModalVisible} good={currentGood} setVisible={setVisible}></Edit>
      <Table columns={columns} dataSource={goodsList} className="storage-table"/>
    </>
  )
}

export default Storage